package org.kyw.basic.service.impl;

import org.kyw.basic.constant.LoginConstant;
import org.kyw.basic.exception.BusinessException;
import org.kyw.basic.service.IVerifycodeService;
import org.kyw.basic.util.SmsUtils;
import org.kyw.basic.util.StrUtils;
import org.kyw.user.domain.User;
import org.kyw.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void settlement(Map<String, String> param) {
        String phone = param.get("phone");
        String type = param.get("type");

        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(type)){
            throw new BusinessException("参数不能为空");
        }
        String businessKey = "";
        if("register".equals(type)){
            User user = userMapper.loadByPhone(phone);
            if(user != null){
                throw new BusinessException("手机号已经注册，请直接登录");
            }

            businessKey = LoginConstant.PHONE_REGISTER + phone;
        }else if ("binder".equals(type)){
            businessKey = LoginConstant.PHONE_BINDER + phone;
        }

        sendCode(businessKey);
    }

    public void sendCode(String businessKey) {
        Object codeTmp = redisTemplate.opsForValue().get(businessKey);

        String code = "";
        if(codeTmp != null) {
            Long oldSendTime = Long.valueOf(codeTmp.toString().split(":")[1]);
            if((System.currentTimeMillis() - oldSendTime.longValue()) <= 1*60*1000) {
                throw new BusinessException("请勿重复获取验证码");
            }
            code = codeTmp.toString().split(":")[0];
        } else {
            code = StrUtils.getComplexRandomString(4);
        }

        String codeValue = code + ":" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(
                businessKey,
                codeValue,
                3,
                TimeUnit.MINUTES);

        //SmsUtils.sendSms(phone, "您的宠物乐园平台的注册验证码是：" + code + "，请在3分钟内使用");
        System.out.println("您的宠物乐园平台的注册验证码是：" + code + "，请在3分钟内使用");
    }
}
